from threading import Timer
import os
import time

# 存放一些简单的通用类或者方法

class RepeatedTimer(object):
    # https://stackoverflow.com/questions/3393612/run-certain-code-every-n-seconds
    def __init__(self, interval, function, *args, **kwargs):
        self._timer     = None
        self.interval   = interval
        self.function   = function
        self.args       = args
        self.kwargs     = kwargs
        self.is_running = False

    def _run(self):
        self.is_running = False
        self.start()
        self.function(*self.args, **self.kwargs)

    def start(self):
        if not self.is_running:
            self._timer = Timer(self.interval, self._run)
            self._timer.start()
            self.is_running = True

    def stop(self):
        self._timer.cancel()
        self.is_running = False

# Python递归遍历目录下所有文件查找指定文,找到则返回
# ref: https://blog.csdn.net/abc_12366/article/details/80101233
def search_file(root, target):
    items = os.listdir(root)
    for item in items:
        path = os.path.join(root, item)
        if os.path.isdir(path):
            # print('[-]', path)
            return search_file(path, target)
        elif target in path:
            # print('[+]', path)
            return path
        else:
            # print('[!]', path)
            pass

#时间戳转为格式化时间
def timestamp_to_time(timestamp):
    time_struct = time.localtime(timestamp)
    return time.strftime('%Y-%m-%d %H:%M:%S',time_struct)

import logging
import re
from logging.handlers import TimedRotatingFileHandler
# https://blog.csdn.net/energysober/article/details/53263295
def initLogging(logFilename):
    log_fmt = 'file:\"%(filename)s\", line %(lineno)s\t%(levelname)s: %(message)s'
    logging.basicConfig(level= logging.INFO,
                        format=log_fmt)
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter(log_fmt)
    console.setFormatter(formatter)
    logging.getLogger().addHandler(console)
    
    # 写文件
    log_fmt = '%(asctime)s\tfile:\"%(filename)s\", line %(lineno)s\t%(levelname)s: %(message)s'
    formatter = logging.Formatter(log_fmt)
    log_file_handler = TimedRotatingFileHandler(filename=logFilename, when="D", interval=1, backupCount=7)
    log_file_handler.suffix = "%Y-%m-%d_%H-%M.log"
    log_file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}.log$")
    log_file_handler.setFormatter(formatter)
    log_file_handler.setLevel(logging.INFO)
    logging.getLogger().addHandler(log_file_handler)


